/*
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 * SPDX-License-Identifier: Apache-2.0
 * Copyright (c) 2023-2024 Jeremy Long. All Rights Reserved.
 */
package io.github.jeremylong.openvulnerability.client.epss;

import io.github.jeremylong.openvulnerability.client.DataFeed;
import io.github.jeremylong.openvulnerability.client.HttpClientSupplier;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;

import java.io.IOException;
import java.util.List;

/**
 * Data Feed for the Exploit Prediction Scoring System (EPSS) scores from the Forum of Incident Response and Security
 * Teams (FIRST)
 *
 * @see <a href="https://www.first.org/epss/data_stats">https://www.first.org/epss/data_stats</a>
 */
public class EpssDataFeed implements DataFeed<List<EpssItem>> {
    private final static String DEFAULT_LOCATION = "https://epss.cyentia.com/epss_scores-current.csv.gz";

    private final HttpClientSupplier httpClientSupplier;
    private final String downloadUrl;

    public EpssDataFeed() {
        this(DEFAULT_LOCATION);
    }

    public EpssDataFeed(String downloadUrl) {
        this(downloadUrl, null);
    }

    public EpssDataFeed(String downloadUrl, HttpClientSupplier httpClientSupplier) {
        this.downloadUrl = downloadUrl;
        this.httpClientSupplier = httpClientSupplier != null ? httpClientSupplier : HttpClientSupplier.getDefault();
    }

    @Override
    public List<EpssItem> download() {
        List<EpssItem> list = null;
        HttpGet request = new HttpGet(downloadUrl);
        try (CloseableHttpClient client = httpClientSupplier.get()) {
            list = client.execute(request, new EpssResponseHandler());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
}
